﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace MvcWechat.Common
{
    public class CommonPage
    {
        public static string XIANHUO = "现货单";
        public static string XIAOSHOU = "销售订单";
        public static string CAIGOU = "采购订单";
        public static string QUHUO = "取货单";
        public static string ALL = "全部订单";


        public static string UPLOAD_TEMPLATE = "UPLOADTEMPLATE";
        public static string ENTRY_TEMPLATE = "ENTRYTEMPLATE";


        public static string msgInfo = "{{\"msgcode\":{0},\"msginfo\":\"{1}\"}}";

        private static object ojb = new object();

        public static string flag { private set; get; }
        
        public static string domainName { private set;get;}
        public static Dictionary<string, string> DomainDict { private set; get; }
        public static string IndexImgPath = ConfigurationManager.AppSettings["IndexImgPath"] == null ? "/ico/" : ConfigurationManager.AppSettings["IndexImgPath"];

        public static Dictionary<string, ConfigSettings> SuppplierAllKey { private set; get; }
        public static Dictionary<string, bool> DictShowSales { private set; get; }

        public static string getKey()
        {
            //不是正式
            if (flag != "true")
                return "YDT";
            //线上正式
            string url = HttpContext.Current.Request.Url.Authority.ToLower();
            //如果为空，让它直接报错
            return DomainDict[url];
        }


        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="name"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string downLoad(string name, string json)
        {
            string inputJson = "";
            if (json != "")
            {
                if (json == "false")
                {
                    inputJson = string.Format(msgInfo, "false", "导出" + name + "失败!");
                    return inputJson;
                }
                //文件名
                string filename = name + "_" + DateTime.Now.ToString("yyyyMMddHHmmsss") + ".xls";
                string today = DateTime.Now.ToString("yyyyMMdd");
                //文件夹路径
                string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~") + "Content/DownLoad/data/");
                string allFilePath = filePath + today + "/";
                if (!Directory.Exists(allFilePath))
                {
                    Directory.CreateDirectory(allFilePath);
                }
                else
                {
                    DirectoryInfo dir = new DirectoryInfo(filePath);
                    DirectoryInfo[] childs = dir.GetDirectories();
                    foreach (DirectoryInfo child in childs)
                    {
                        //只保留单日的下载文件
                        if (child.Name != today)
                        {
                            child.Delete(true);
                        }
                    }
                }
                string fullpath = allFilePath + filename;
                StreamWriter sw = new StreamWriter(fullpath, false, Encoding.GetEncoding(-0));
                sw.Write(json);
                sw.Close();
                string urls = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Replace(System.Web.HttpContext.Current.Request.Url.LocalPath, "");

                string path = urls + "/Content/DownLoad/data/" + today + "/" + filename;

                inputJson = string.Format(msgInfo, "true", path);
                return inputJson;
            }
            else
            {
                inputJson = string.Format(msgInfo, "false", "今日无" + name);
                return inputJson;
            }
        }
        /// <summary>
        /// 下载模板
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string DownTemplate(string type)
        {
            try
            {
                string FileName = getTemplateFile(type);
                string filePath = "/Content/DownLoad/Template/";
                string urls = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Replace(System.Web.HttpContext.Current.Request.Url.LocalPath, "");
                string path = Path.Combine(HttpContext.Current.Server.MapPath("~") + filePath);
                if (!File.Exists(path + FileName))
                {
                    return string.Format(msgInfo, "false", "下载失败，文件不存在");
                }
                return string.Format(msgInfo, "true", urls + filePath + FileName);
            }
            catch (Exception ex)
            {
                return string.Format(msgInfo, "false", "下载失败，文件不存在");
            }
        }
        /// <summary>
        /// 获取下载模板文件名
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string getTemplateFile(string type)
        {
            string FileName = "";
            if (type == UPLOAD_TEMPLATE)
                FileName = "upload_template.xls";//文件名
            else if (type == ENTRY_TEMPLATE)
                FileName = "entry_template.xls";//文件名

            return FileName;
        }

        public static string readXMLFile(string key)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath("~") + @"Language\" + key + "CommonXML.xml"))
            {
                string xmlFile = "";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(HttpContext.Current.Server.MapPath("~") + @"Language\" + key + "CommonXML.xml");
                XmlNode root = xmlDoc.SelectSingleNode("ROOT/" + key);
                XmlNodeList list = root.ChildNodes;
                foreach (XmlNode r in list)
                {
                    if (r.ChildNodes.Count > 0)
                    {
                        XmlNodeList rlist = r.ChildNodes;
                        foreach (XmlNode z in rlist)
                        {
                            if (!string.IsNullOrEmpty(z.InnerText))
                            {
                                z.InnerText = ("," + z.InnerText).Replace(",", "," + r.Name + ".");
                                xmlFile += z.InnerText;
                            }
                        }
                    }
                }
                System.Web.HttpContext.Current.Cache.Insert("Cache:xmlFile" + key, xmlFile, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
                return xmlFile;
            }
            return "";
        }

        /// <summary>
        /// true有更新，false 没有更新
        /// </summary>
        /// <returns>true有更新，false 没有更新</returns>
        public static bool GetVersion(string key)
        {
            //这个函数不需要加version，之前想的是可能所有的分开设置version
            if (System.Web.HttpContext.Current.Cache.Get("Cache:Version" + key) == null)
            {
                string strVersion = ConfigurationManager.AppSettings["Version"];
                System.Web.HttpContext.Current.Cache.Insert("Cache:Version" + key, strVersion, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
                return true;
            }
            else
            {
                string newVersion = ConfigurationManager.AppSettings["Version"];
                if (System.Web.HttpContext.Current.Cache.Get("Cache:Version" + key).ToString() != newVersion)
                {
                    System.Web.HttpContext.Current.Cache.Insert("Cache:Version" + key, newVersion, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
                    return true;
                }
                else
                    return false;
            }
        } 
        public static string GetSectionConfig()
        { 
            string key = getKey();
            ConfigSettings configSetting = ConfigurationManager.GetSection(key) as ConfigSettings;
            if (configSetting == null)
                return "diamond";
            return configSetting.Menus;
             
 
        }
        public static ConfigSettings GetConfigSettings()
        {
            return SuppplierAllKey[getKey()];
            //CommonPage cp = new CommonPage();
            //string key = cp.getKey();
            //var config = WeixinConfigs.listConfigSettings[key];
            //return config;
        }
        public static void Register()
        {
            //是否调试模式
            flag = ConfigurationManager.AppSettings["IsUseDomainName"];
            //所有url列表
            domainName = ConfigurationManager.AppSettings["DomainName"];
            DomainDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(domainName);
            Dictionary<string, ConfigSettings> configSettings = new Dictionary<string, ConfigSettings>();
            var list = JsonConvert.DeserializeObject<Dictionary<string, string>>(domainName);
            foreach (var item in list)
            {
                if (!configSettings.ContainsKey(item.Value))
                {
                    ConfigSettings configSetting = ConfigurationManager.GetSection(item.Value) as ConfigSettings;
                    configSettings.Add(item.Value, configSetting);
                }
            }
            SuppplierAllKey = configSettings;
             
        } 
        /// <summary>
        /// 获取模板
        /// </summary>
        /// <returns></returns>
        public static string GetIsHideSupplier()
        {
            string key = CommonPage.getKey();
            //供应商的KEY 包含下划线就标识二级 一级的KEY 不能有下划线
            if (key.Contains("__"))
                return "2";
            else
                return "1";
        }

    }

    public class JsonK : JsonResult
    {
        public static JsonResult Json(object data,JsonRequestBehavior behavior)
        {
            JsonResult json = new JsonResult();
            json.MaxJsonLength = int.MaxValue;
            json.Data = data;
            json.JsonRequestBehavior = behavior;
            return json;
        }
    }
}